package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.InfoDataDetailActivity;
import com.jp.knowledge.activity.KnowlageDetailActivity;
import com.jp.knowledge.activity.VipZoneShowActivity;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.VipZoneAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.DailyKnowledgePackageModel;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.KnowlageListModel;
import com.jp.knowledge.model.KnowlageModel;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/6/14.
 */

public class VipZoneFragment extends BaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener {

    public static VipZoneFragment newInstance(String id, String packageId){
        VipZoneFragment fragment = new VipZoneFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("packageId", packageId);
        fragment.setArguments(bundle);
        return fragment;
    }

    protected Context mContext;
	protected View contentView;
	protected CanRefreshLayout refreshLayout;
    private JpRefreshView footerView;
	protected RecyclerView refreshContent;

    private String packageId;
	protected int page;
	protected List<KnowlageListModel> datas;
	protected VipZoneAdapter adapter;
    protected String cachePath;
	protected FileCacheManager cacheManager;
    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    public String getPackageId() {
        return packageId;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(mContext == null){
            mContext = getContext();
            packageId = getArguments().getString("packageId");
            page = 1;
            datas = new ArrayList<>();

            contentView = View.inflate(mContext, R.layout.refresh_recycleview, null);
            contentView.setBackgroundColor(getResources().getColor(R.color.white));
            refreshLayout = (CanRefreshLayout) contentView.findViewById(R.id.refresh);
            refreshContent = (RecyclerView) contentView.findViewById(R.id.can_content_view);
            footerView = (JpRefreshView) contentView.findViewById(R.id.can_refresh_footer);
            refreshLayout.setOnRefreshListener(this);
            refreshLayout.setOnLoadMoreListener(this);
            refreshContent.setHasFixedSize(true);
            refreshContent.setLayoutManager(new LinearLayoutManager(mContext));

            adapter = new VipZoneAdapter(mContext, datas);
            adapter.setOnItemListener(new OnItemListerner() {
                @Override
                public void onItemClick(View view, int position) {
                    HeadLineData headLineData = datas.get(position);

                    if(headLineData.getLayout() == 5){
                        Intent intent = new Intent(mContext, KnowlageDetailActivity.class);
                        intent.putExtra("cataId", headLineData.getId());
                        intent.putExtra("packageId", headLineData.getPackageId());
                        intent.putExtra("title", headLineData.getTitle());
                        startActivity(intent);
                    } else{
//                        Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
//                        intent.putExtra("id", headLineData.getId());
//                        intent.putExtra("type", headLineData.getType());
//                        intent.putExtra("linkTitle", headLineData.getTitle());
//                        try {
//                            intent.putExtra("linkIcon", headLineData.getImglist().get(0).getSrc());
//                        } catch (Exception e){} finally {
//                            startActivity(intent);
//                        }
                        CommandReceiver commandReceiver = new CommandReceiver.Builder(mContext)
                                .withCompanyId(headLineData.getCompanyId())
                                .withRecordId(headLineData.getRecordId())
                                .withParameterId(headLineData.getParameterId() + "")
                                .build();
                        Command commandObject = Command.create(headLineData.getCommand(), commandReceiver);
                        CommandInvoker.executeCommand(commandObject);
                    }
                }
            });
            refreshContent.setAdapter(adapter);
            initBroadcast();
            initCache();
            readCache();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return contentView;
    }

    private void initBroadcast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                if(LocalBroadCast.COMM_CHANGE_SIZE.equals(intent.getAction()))
                    adapter.changeTextSize();
            }
        });
        localBroadcastManager.registerReceiver(localBroadCast, new IntentFilter(LocalBroadCast.COMM_CHANGE_SIZE));;
    }

    protected void initCache(){
        cacheManager = new FileCacheManager();
        cachePath = mContext.getCacheDir() + "/vipZoneData_" + HttpHelper.uuid + "_" + packageId + ".dat";
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<KnowlageListModel>>() {
            @Override
            public void call(Subscriber<? super List<KnowlageListModel>> subscriber) {
                List<KnowlageListModel> data = (List<KnowlageListModel>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<KnowlageListModel>>() {
            @Override
            public void onCompleted() {
                if(datas.size() == 0)
                    refreshLayout.autoRefresh();
                else
                    onRefresh();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<KnowlageListModel> data) {
                if(data != null) {
                    datas.addAll(data);
                    adapter.updataAdapter(datas);
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<KnowlageListModel> saveDatas = new ArrayList<>();
                if (datas.size() > 20)
                    for (int i = 0; i < 19; i++)
                        saveDatas.add(datas.get(i));
                else
                    saveDatas.addAll(datas);
                cacheManager.wirteObject(saveDatas, cachePath);
            }
        }).start();
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData(page);
    }

    @Override
    public void onLoadMore() {
        if(footerView.isLoadComplete())
            refreshLayout.loadMoreComplete();
        else
            getData(++page);
    }

    protected void getData(int page){
        JsonObject param  = new JsonObject();
        param.addProperty("packageId", packageId);
        param.addProperty("page", page);
        HttpHelper.getInstance(mContext).knowledgePackage(param, page, this);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == 1)
            refreshLayout.refreshComplete();
        else
            refreshLayout.loadMoreComplete();
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else{
            if(requestType == 1) {
                footerView.setLoadComplete(false);
                datas.clear();
            }
            KnowlageModel tmpData = data.getEntity(KnowlageModel.class);
            if(tmpData != null && tmpData.getList() != null && tmpData.getList().size() > 0)
                datas.addAll(tmpData.getList());
            else if(requestType != 1)
                footerView.setLoadComplete(true);
            adapter.updataAdapter(datas);
        }
    }
}
